import os
from index import library_data, LibraryUI
from function import LibraryFunctions
import tkinter as tk
from tkinter import messagebox, ttk

class LibraryManager:
    def __init__(self, ui):
        self.ui = ui
        try:
            self.data = library_data
            self._setup_callbacks()
            self.refresh_all()
        except Exception as e:
            messagebox.showerror("初始化错误", f"系统初始化失败: {e}")
            self.ui.root.destroy()

    def _setup_callbacks(self):
        """设置所有UI回调"""
        callbacks = {
            'view_student_details': self.view_student_details,
            'refresh_students': self.refresh_students,
            'view_book_details': self.view_book_details,
            'refresh_books': self.refresh_books,
            'search_books': self.search_books,
            'borrow_book': self.borrow_book,
            'return_book': self.return_book,
            'reserve_book': self.reserve_book,
            'report_lost': self.report_lost,
            'refresh_stats': self.refresh_stats
        }
        
        for name, callback in callbacks.items():
            setattr(self.ui, name, callback)

    def refresh_all(self):
        """刷新所有数据"""
        self.refresh_students()
        self.refresh_books()
        self.refresh_stats()
    
    def refresh_students(self):
        """刷新学生列表"""
        self.ui.student_tree.delete(*self.ui.student_tree.get_children())
        for student in self.data["students"]:
            self.ui.student_tree.insert("", "end", values=(
                student["id"],
                student["name"],
                student["age"],
                len(student["borrowed_books"]),
                student["credit_points"]
            ))
    
    def refresh_books(self):
        """刷新图书列表"""
        self.ui.book_tree.delete(*self.ui.book_tree.get_children())
        for book in self.data["books"]:
            if "available_copies" not in book:
                book["available_copies"] = book["number_of_copies"]
            
            self.ui.book_tree.insert("", "end", values=(
                book["title"],
                ", ".join(book["authors"]),
                book["year"],
                f"{book['available_copies']}/{book['number_of_copies']}"
            ))
    
    def refresh_stats(self):
        """刷新统计信息"""
        self.ui.popular_list.delete(0, tk.END)
        
        borrow_counts = {}
        for book in self.data["books"]:
            borrow_counts[book["title"]] = book["number_of_copies"] - book.get("available_copies", book["number_of_copies"])
        
        for book, count in sorted(borrow_counts.items(), key=lambda x: x[1], reverse=True)[:5]:
            self.ui.popular_list.insert(tk.END, f"{book} - 借出次数: {count}")
    
    def view_student_details(self):
        """查看学生详情"""
        selected = self.ui.student_tree.selection()
        if not selected:
            return
        
        student_id = self.ui.student_tree.item(selected[0])["values"][0]
        student = LibraryFunctions.find_item(
            self.data["students"],
            lambda s: s["id"] == student_id
        )
        
        if not student:
            return
        
        detail_win = tk.Toplevel(self.ui.root)
        detail_win.title(f"学生详情 - {student['name']}")
        detail_win.geometry("500x400")
        
        ttk.Label(detail_win, text=f"姓名: {student['name']}").pack(pady=5)
        ttk.Label(detail_win, text=f"年龄: {student['age']}").pack(pady=5)
        ttk.Label(detail_win, text=f"学校: {student['school']}").pack(pady=5)
        
        # 显示借阅的书籍
        ttk.Label(detail_win, text="已借书籍:").pack(pady=5)
        borrowed_list = tk.Listbox(detail_win)
        for book in student["borrowed_books"]:
            borrowed_list.insert(tk.END, book)
        borrowed_list.pack(fill="both", expand=True, padx=10, pady=5)
    
    def view_book_details(self):
        """查看图书详情"""
        selected = self.ui.book_tree.selection()
        if not selected:
            return
        
        book_title = self.ui.book_tree.item(selected[0])["values"][0]
        book = LibraryFunctions.find_item(
            self.data["books"],
            lambda b: b["title"] == book_title
        )
        
        if not book:
            return
        
        detail_win = tk.Toplevel(self.ui.root)
        detail_win.title(f"图书详情 - {book['title']}")
        detail_win.geometry("600x500")
        
        ttk.Label(detail_win, text=f"书名: {book['title']}", font=('Arial', 12, 'bold')).pack(pady=5)
        ttk.Label(detail_win, text=f"作者: {', '.join(book['authors'])}").pack(pady=5)
        ttk.Label(detail_win, text=f"出版年份: {book['year']}").pack(pady=5)
        ttk.Label(detail_win, text=f"类别: {book['category']} - {book['sub_category']}").pack(pady=5)
        ttk.Label(detail_win, text=f"语言: {book['language']}").pack(pady=5)
        ttk.Label(detail_win, text=f"页数: {book['page_count']}").pack(pady=5)
        ttk.Label(detail_win, text=f"可借数量: {book.get('available_copies', book['number_of_copies'])}/{book['number_of_copies']}").pack(pady=5)
        
        # 显示关键词
        ttk.Label(detail_win, text="关键词:").pack(pady=5)
        keywords_frame = ttk.Frame(detail_win)
        for keyword in book["keywords"]:
            ttk.Label(keywords_frame, text=keyword, relief="solid", padding=3).pack(side="left", padx=3)
        keywords_frame.pack()
        
        # 显示摘要
        ttk.Label(detail_win, text="摘要:").pack(pady=5)
        summary = tk.Text(detail_win, wrap="word", height=8)
        summary.insert("1.0", book["summary"])
        summary.config(state="disabled")
        summary.pack(fill="both", expand=True, padx=10, pady=5)
    
    def search_books(self):
        """搜索图书"""
        search_term = self.ui.book_search_entry.get().strip()
        if not search_term:
            self.refresh_books()
            return

        search_key = self.ui.search_option.get()
        results = []

        for book in self.data["books"]:
            if search_key == "title" and search_term.lower() in book["title"].lower():
                results.append(book)
            elif search_key == "authors" and any(search_term.lower() in author.lower() for author in book["authors"]):
                results.append(book)
            elif search_key == "year":
                try:
                    if book["year"] == int(search_term):
                        results.append(book)
                except ValueError:
                    pass

        self.ui.book_tree.delete(*self.ui.book_tree.get_children())
        for book in results:
            self.ui.book_tree.insert("", "end", values=(
                book["title"],
                ", ".join(book["authors"]),
                book["year"],
                f"{book.get('available_copies', book['number_of_copies'])}/{book['number_of_copies']}"
            ))
    
    def borrow_book(self):
        """借书功能"""
        student_id = self.ui.borrow_student_entry.get().strip()
        book_title = self.ui.borrow_book_entry.get().strip()
        
        if not student_id or not book_title:
            messagebox.showwarning("警告", "请输入用户名和图书名称")
            return
        
        student = LibraryFunctions.find_item(
            self.data["students"],
            lambda s: s["id"] == student_id
        )
        
        book = LibraryFunctions.find_item(
            self.data["books"],
            lambda b: b["title"] == book_title
        )
        
        if not student:
            messagebox.showerror("错误", "找不到该学生")
            return
        
        if not book:
            messagebox.showerror("错误", "找不到该图书")
            return
        
        if book.get("available_copies", book["number_of_copies"]) <= 0:
            messagebox.showwarning("警告", "该书已全部借出")
            return
        
        if len(student["borrowed_books"]) >= 5:
            messagebox.showwarning("警告", "每个学生最多只能借5本书")
            return
        
        if book_title in student["borrowed_books"]:
            messagebox.showwarning("警告", "该学生已经借阅了这本书")
            return
        
        # 执行借书操作
        book["available_copies"] = book.get("available_copies", book["number_of_copies"]) - 1
        student["borrowed_books"].append(book_title)
        
        # 检查是否有等待列表
        if book_title in student["waiting_list"]:
            student["waiting_list"].remove(book_title)
        
        messagebox.showinfo("成功", f"借书成功: {book_title}")
        self.refresh_all()
    
    def return_book(self):
        """还书功能"""
        student_id = self.ui.return_student_entry.get().strip()
        book_title = self.ui.return_book_entry.get().strip()
        
        if not student_id or not book_title:
            messagebox.showwarning("警告", "请输入用户名和图书名称")
            return
        
        student = LibraryFunctions.find_item(
            self.data["students"],
            lambda s: s["id"] == student_id
        )
        
        book = LibraryFunctions.find_item(
            self.data["books"],
            lambda b: b["title"] == book_title
        )
        
        if not student:
            messagebox.showerror("错误", "找不到该学生")
            return
        
        if not book:
            messagebox.showerror("错误", "找不到该图书")
            return
        
        if book_title not in student["borrowed_books"]:
            messagebox.showwarning("警告", "该学生没有借阅这本书")
            return
        
        # 执行还书操作
        book["available_copies"] = book.get("available_copies", book["number_of_copies"]) + 1
        student["borrowed_books"].remove(book_title)
        
        messagebox.showinfo("成功", f"还书成功: {book_title}")
        self.refresh_all()
    
    def reserve_book(self):
        """预约图书"""
        student_id = self.ui.reserve_student_entry.get().strip()
        book_title = self.ui.reserve_book_entry.get().strip()
        
        if not student_id or not book_title:
            messagebox.showwarning("警告", "请输入用户名和图书名称")
            return
        
        student = LibraryFunctions.find_item(
            self.data["students"],
            lambda s: s["id"] == student_id
        )
        
        book = LibraryFunctions.find_item(
            self.data["books"],
            lambda b: b["title"] == book_title
        )
        
        if not student:
            messagebox.showerror("错误", "找不到该学生")
            return
        
        if not book:
            messagebox.showerror("错误", "找不到该图书")
            return
        
        if book_title in student["waiting_list"]:
            messagebox.showwarning("警告", "该学生已经在等待列表中")
            return
        
        if book_title in student["borrowed_books"]:
            messagebox.showwarning("警告", "该学生已经借阅了这本书")
            return
        
        # 添加到等待列表
        student["waiting_list"].append(book_title)
        messagebox.showinfo("成功", f"已添加到等待列表: {book_title}")
        self.refresh_all()
    
    def report_lost(self):
        """报告遗失"""
        student_id = self.ui.lost_student_entry.get().strip()
        book_title = self.ui.lost_book_entry.get().strip()
        
        if not student_id or not book_title:
            messagebox.showwarning("警告", "请输入用户名和图书名称")
            return
        
        student = LibraryFunctions.find_item(
            self.data["students"],
            lambda s: s["id"] == student_id
        )
        
        book = LibraryFunctions.find_item(
            self.data["books"],
            lambda b: b["title"] == book_title
        )
        
        if not student:
            messagebox.showerror("错误", "找不到该学生")
            return
        
        if not book:
            messagebox.showerror("错误", "找不到该图书")
            return
        
        if book_title not in student["borrowed_books"]:
            messagebox.showwarning("警告", "该学生没有借阅这本书")
            return
        
        # 执行遗失报告
        student["borrowed_books"].remove(book_title)
        book["number_of_copies"] -= 1
        student["credit_points"] -= 1  # 扣除信用积分
        
        messagebox.showinfo("成功", f"已报告遗失: {book_title}\n信用积分已扣除1分")
        self.refresh_all()

def main():
    root = tk.Tk()
    ui = LibraryUI(root)
    manager = LibraryManager(ui)
    root.mainloop()

if __name__ == "__main__":
    main()